ngx.header.content_type="application/json;charset=utf8"
local cjson = require("cjson")
local mysql = require("resty.mysql")
local mysql_pool = {}  --初始化连接池
-- 获取用户请求的参数 (请求url链接的"?"后的参数)
local uri_args = ngx.req.get_uri_args()
-- 请求参数里的"id"参数的值
local id = uri_args["id"]

function mysql_pool:get_connect()  --conf 为数据库的配置
    if ngx.ctx[mysql_pool] then  
        return true, ngx.ctx[mysql_pool]  
    end  
    local client, errmsg = mysql:new()  
    if not client then  
        return false, "mysql.socket_failed: " .. (errmsg or "nil")  
    end  
  
    client:set_timeout(10000)  --设置超时时间
	local options = {
		host = "47.96.8.149",
		port = 3306,
		database = "his_cloud_agent",
		user = "root",
		password = "lulutong321"
	}
    local result, errmsg, errno, sqlstate = client:connect(options)  
    if not result then  
        return false, "mysql.cant_connect: " .. (errmsg or "nil") .. ", errno:" .. (errno or "nil") .. ", sql_state:" .. (sqlstate or "nil")  
    end  
  
    local query = "SET NAMES " .. "utf8"  
    local result, errmsg, errno, sqlstate = client:query(query)  
    if not result then  
        return false, "mysql.query_failed: " .. (errmsg or "nil") .. ", errno:" .. (errno or "nil") .. ", sql_state:" .. (sqlstate or "nil")  
    end  
    ngx.ctx[mysql_pool] = client  
    -- 测试，验证连接池重复使用情况  
    --[[
    local count, err = client:get_reused_times()  
    ngx.say("xxx reused times" .. count);  
    --]]  
  
    return true, ngx.ctx[mysql_pool]  
end
function mysql_pool:close()  
    if ngx.ctx[mysql_pool] then 
        ngx.ctx[mysql_pool]:set_keepalive(60000, 80)  
        ngx.ctx[mysql_pool] = nil  
    end  
end
function mysql_pool:query(sql)  --sql 传入sql语句  conf 数据库配置文件
    local ret, client = self:get_connect()  
    if not ret then  
        return false, client, nil  
    end  
  
    local result, errmsg, errno, sqlstate = client:query(sql)  
  
    while errmsg == "again" do  
        result, errmsg, errno, sqlstate = client:read_result()  
    end  
  
    self:close()  
  
    if not result then  
        errmsg = "mysql.query_failed:" .. (errno or "nil") .. (errmsg or "nil")  
        return false, errmsg, sqlstate  
    end  
  
    return true, result, sqlstate  
end  
-- sql语句
local select_sql = "SELECT * FROM dic_agent_subject WHERE agent_id ="..ngx.quote_sql_str(id)
local flag ,result,sqlstate = mysql_pool:query(select_sql)
ngx.say(cjson.encode(result))
